package com.stadium.web.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fastsite.common.api.ApiResult;
import com.fastsite.common.api.ApiSecured;
import com.fastsite.common.api.ApiTokenUser;
import com.fastsite.common.domain.TokenUserObject;
import com.fastsite.common.enums.StatusEnum;
import com.stadium.web.domain.MarketActivity;
import com.stadium.web.domain.User;
import com.stadium.web.domain.Venue;
import com.stadium.web.service.MarketActivityService;
import com.stadium.web.service.VenueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 营销活动对象 market_activity
 *
 * @author ruoyi
 * @date 2020-03-15
 */
@Validated
@Api(tags = "营销活动管理")
@RestController
@RequestMapping("/web/activity")
public class MarketActivityController {

    @Autowired
    private MarketActivityService marketActivityService;

    @Autowired
    private VenueService venueService;
    /**
     * 列表页面
     */
    @ApiOperation("营销活动列表信息")
    @ApiImplicitParams({
    @ApiImplicitParam(name="page",value="当前页数",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="size",value="每页的数量",required=false,paramType="form",dataType="Long"),
//    @ApiImplicitParam(name="id",value="ID",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="venueId",value="所属场馆",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="name",value="活动名称",required=false,paramType="form",dataType="String"),
    @ApiImplicitParam(name="discount",value="优化力度",required=false,paramType="form",dataType="Double"),
    @ApiImplicitParam(name="fromTime",value="活动开始时间",required=false,paramType="form",dataType="Date"),
    @ApiImplicitParam(name="toTime",value="活动结束时间",required=false,paramType="form",dataType="Date"),
    })
    @GetMapping("/list")
    public ApiResult index(@ApiIgnore MarketActivity marketActivity){

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();

        // 获取营销活动列表
        Example<MarketActivity> example = Example.of(marketActivity, matcher);
        Page<MarketActivity> list = marketActivityService.getPageList(example);

        HashMap<String,Object> result = new HashMap<>();
        result.put("list", list.getContent());
        result.put("page", list);
        // 封装数据
        return ApiResult.ok(result,"获取营销活动列表信息");
    }

    /**
     * 跳转到编辑页面
     */
    @ApiOperation("单个营销活动信息")
    @GetMapping("/getOneMarketActivity")
    public ApiResult toEdit(@RequestParam("id") Long id){
        MarketActivity marketActivity=  marketActivityService.getById(id);
        return ApiResult.ok(marketActivity,"获取单个营销活动");
    }

    /**
     * 保存添加/修改的数据
     * @param marketActivityFrom 实体对象
     */
    @ApiSecured
    @ApiOperation(value = "保存/修改单个营销活动", authorizations = @Authorization(value = "token"), produces =  MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//    @ApiImplicitParam(name="id",value="ID",required=false,paramType="body",dataType="Long"),
//    @ApiImplicitParam(name="venueId",value="所属场馆",required=false,paramType="body",dataType="Long"),
//    @ApiImplicitParam(name="name",value="活动名称",required=false,paramType="body",dataType="String"),
//    @ApiImplicitParam(name="discount",value="优化力度",required=false,paramType="body",dataType="Double"),
//    @ApiImplicitParam(name="fromTime",value="活动开始时间",required=false,paramType="body",dataType="Date"),
//    @ApiImplicitParam(name="toTime",value="活动结束时间",required=false,paramType="body",dataType="Date"),
//    })
    @PostMapping({"/save","/update"})
    @ResponseBody
    public ApiResult save(@ApiTokenUser TokenUserObject<User> user, @Valid @RequestBody MarketActivityForm marketActivityFrom){
        MarketActivity marketActivity = null;
        Venue venue = venueService.findByUserIdAndVenueId(user.getId(),marketActivityFrom.getVenueId());
        if(venue == null){
            return ApiResult.err("没有该场馆得权限");
        }

        if(!StringUtils.isEmpty(marketActivityFrom.getId())){
            //修改
            marketActivity = marketActivityService.getById(marketActivityFrom.getId());

            marketActivity.setId(marketActivityFrom.getId());
                marketActivity.setVenueId(marketActivityFrom.getVenueId());
                marketActivity.setName(marketActivityFrom.getName());
                marketActivity.setDiscount(marketActivityFrom.getDiscount());
                marketActivity.setFromTime(marketActivityFrom.getFromTime());
                marketActivity.setToTime(marketActivityFrom.getToTime());
            }else{
            //新增
            marketActivity = new MarketActivity();
            BeanUtils.copyProperties(marketActivityFrom,marketActivity);
        }
        // 保存数据
        marketActivityService.save(marketActivity);
        return ApiResult.ok("保存成功");
    }


    /**
     * 设置一条或者多条数据的状态
     */

    @ApiOperation(value = "修改营销活动状态",hidden=true)
    @ApiImplicitParams({
            @ApiImplicitParam(name="param",value="状态（1:正常，2:冻结,3:删除）",required=true,paramType="path",dataType="String"),
            @ApiImplicitParam(name="ids",value="修改[id]",required=true,paramType="form",dataType="List")}
    )
    @RequestMapping(value = "/status/{param}",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ApiResult status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids){
        // 更新状态
        StatusEnum statusEnum = StatusEnum.getByCode(Byte.parseByte(param));
        if (marketActivityService.updateStatus(statusEnum, ids)) {
            return ApiResult.ok(statusEnum.getMessage() + "成功");
        } else {
            return ApiResult.err(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}

@Data
@ApiModel("优惠信息表单")
class MarketActivityForm{
    /** ID */
    @ApiModelProperty("ID")
    private Long id;

    /** 所属场馆 */
    @ApiModelProperty(value = "所属场馆",required = true)
    @NotNull(message = "所属场馆不能为空")
    private Long venueId;

    /** 活动名称 */
    @ApiModelProperty(value = "活动名称",required = true)
    private String name;

    /** 优化力度 */

    @ApiModelProperty(value = "优化力度",required = true)
    private Double discount;

    /** 活动开始时间 */
    @JsonFormat(pattern="yyyy-MM-dd  HH:mm")
    @ApiModelProperty(value = "活动开始时间",required = true)
    private Date fromTime;

    /** 活动结束时间 */
    @JsonFormat(pattern="yyyy-MM-dd  HH:mm")
    @ApiModelProperty(value = "活动结束时间",required = true)
    private Date toTime;

}